﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WeixinMP.Interfaces;
using Microhard.Core.DBUtility;
using Microhard.WeixinMP.DataAccess;
using Microhard.WeixinMP.DTO;
using Microhard.Core;
using Microhard.WeixinMP.Models;
using Microhard.WeixinMP.Validators;

namespace Microhard.WeixinMP.Impls
{
    public class WXMPUserImpl : IWXMPUser
    {
        public Core.DBUtility.ExecutedResult Add(Models.WXMPUserModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrohardWXEntities db = new MicrohardWXEntities();
            MPUser op = model.ToEntity();
            op.CreateTime = DateTime.Now;
            op.UpdateTime = DateTime.Now;

            try
            {
                db.MPUsers.AddObject(op);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add("WXMPUserImpl.Add", "微信平台用户添加失败");
                Log.Error("WXMPUserImpl.Add", ex);
            }
            return rtn;
        }

        public Core.DBUtility.ExecutedResult Update(Models.WXMPUserModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrohardWXEntities db = new MicrohardWXEntities();
            try
            {
                var entity = db.MPUsers.SingleOrDefault(c => c.OpenID == model.OpenID);
                //如果数据库存在用户，则做更新
                if (entity != null)
                {
                    entity.FakeID = model.FakeID;
                    entity.UserName = model.UserName;
                    entity.WXMPID = model.WXMPID;
                    entity.UpdateTime = model.UpdateTime;
                    entity.UserName = model.UserName;
                }
                else
                {
                    var newAdd = new MPUser();
                    newAdd.WXUserID = Guid.NewGuid();
                    newAdd.FakeID = model.FakeID;
                    newAdd.OpenID = model.OpenID;
                    newAdd.CreateTime = DateTime.Now;
                    newAdd.UpdateTime = DateTime.Now;
                    db.MPUsers.AddObject(newAdd);
                }

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add("WXMPUserImpl.Update", "微信平台用户修改失败");
                Log.Error("WXMPUserImpl.Update", ex);
            }
            return rtn;
        }

        public Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrohardWXEntities db = new MicrohardWXEntities();
            var toDeltes = from b in db.MPUsers
                           where ids.Contains(b.WXUserID)
                           select b;
            foreach (var d in toDeltes)
            {
                db.MPUsers.DeleteObject(d);
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add("WXMPUserImpl.Delete", "微信平台用户删除失败");
                Log.Error("WXMPUserImpl.Delete", ex);
            }
            return result;
        }

        public Core.DBUtility.ExecutedResult Delete(Models.WXMPUserModel model)
        {
            ExecutedResult result = new ExecutedResult();
            MicrohardWXEntities db = new MicrohardWXEntities();
            var toDelte = db.MPUsers.SingleOrDefault(s => s.OpenID == model.OpenID);
            if (toDelte != null)
            {
                //删除用户
                db.MPUsers.DeleteObject(toDelte);
                //删除消息
                var toDelteMsg = from m in db.MPMessages
                                 where m.OpenID == model.OpenID
                                 select m;
                foreach (var d in toDelteMsg)
                {
                    db.MPMessages.DeleteObject(d);
                }
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add("WXMPUserImpl.Delete", "微信平台用户删除失败");
                    Log.Error("WXMPUserImpl.Delete", ex);
                }
            }
            return result;
        }

        public Models.WXMPUserModel GetModelByID(Guid id)
        {
            var db = new MicrohardWXEntities();
            var entity = db.MPUsers.SingleOrDefault(u => u.WXUserID == id);
            if (entity != null)
                return entity.ToModel();
            return null;
        }

        public Models.WXMPUserModel GetModelByModel(Models.WXMPUserModel model)
        {
            var db = new MicrohardWXEntities();
            var entity = db.MPUsers.SingleOrDefault(u => u.OpenID == model.OpenID);
            if (entity != null)
                return entity.ToModel();
            return null;
        }

        public List<Models.WXMPUserModel> Query(Models.WXMPUserModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrohardWXEntities db = new MicrohardWXEntities();
            IEnumerable<MPUser> entities = from b in db.MPUsers
                                           select b;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<WXMPUserModel>();
        }

        public List<Models.WXMPUserModel> Query(Models.WXMPUserModel Model)
        {
            MicrohardWXEntities db = new MicrohardWXEntities();
            IEnumerable<MPUser> pagedEntities = from b in db.MPUsers
                                           select b;
            return pagedEntities.OrderByDescending(s => s.CreateTime).Select(m => m.ToModel()).ToList();
        }

        public Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }


        public List<WXMPUserModel> GetNewUsers(List<WXMPUserModel> topUsers)
        {
            MicrohardWXEntities db = new MicrohardWXEntities();
            return (from u in db.MPUsers
                    from t in topUsers
                    where u.FakeID != t.FakeID
                    select t).ToList();
        }


        public List<WXMPUserModel> GetNewSubscribes()
        {
            MicrohardWXEntities db = new MicrohardWXEntities();
            return (from u in db.MPUsers
                    where string.IsNullOrEmpty(u.FakeID)
                    select u).ToList().Select(m => m.ToModel()).ToList();
        }

        private bool CheckCreateTime(string fakeIDMsgCreateTime, string openIDMsgCreateTime)
        {
            if (fakeIDMsgCreateTime == openIDMsgCreateTime)
                return true;
            //进行数值+1比较
            long fakeMCT = long.Parse(fakeIDMsgCreateTime);
            fakeMCT = fakeMCT + 1;
            if (fakeMCT.ToString() == openIDMsgCreateTime)
                return true;
            return false;
        }

        public WXMPUserModel CheckUserByCreateTimeAndContent(List<WXMPMessageWithFakeIDModel> msg, RequestServiceModel request)
        {
            WXMPUserModel rtn = new WXMPUserModel();
            var msgTypeValue = System.Configuration.ConfigurationManager.AppSettings[request.MsgType];
            //使用消息类型，创建时间，消息内容进行openid与fakeid的匹配
            var model = msg.SingleOrDefault(s => s.Type == msgTypeValue &&
                this.CheckCreateTime(s.DateTime, request.MsgCreateTime) &&
                (request.MsgType == WeixinMsgType.Text && string.Compare(request.Txt.Content.Content, s.Content) == 0));
            if (model != null)
            {
                rtn.OpenID = request.FromUserName;
                rtn.FakeID = model.FakeId;
                rtn.UpdateTime = DateTime.Now;
                rtn.UserName = model.NickName;
            }
            return rtn;
        }


        public void DeleteMessage(string mpUserOpenID)
        {
            MicrohardWXEntities db = new MicrohardWXEntities();
            var toDeletes = from m in db.MPMessages
                            where m.OpenID == mpUserOpenID
                            select m;
            foreach (var d in toDeletes)
            {
                db.MPMessages.DeleteObject(d);
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error("DeleteMessage", ex);
            }
        }


        public bool IsUserExist(string openID)
        {
            MicrohardWXEntities db = new MicrohardWXEntities();
            int cnt = db.MPUsers.Count(m => m.OpenID == openID);
            return cnt > 0 ? true : false;
        }
    }
}
